package com.alibaba.system.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.system.domain.Role;
import com.alibaba.system.mapper.RoleMapper;
import com.alibaba.system.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addData(role);
    }

    @Override
    @Transactional
    public void update(Role role) {
        //删除旧权限 再添加新权限
        roleMapper.delRoleMenuByRoleID(role.getId());
        roleMapper.delRolePermissionByRoleID(role.getId());
        //再添加新的权限
        addData(role);
        super.update(role); //调用父类方法
    }

    @Override
    public void del(Long id) {//id 是角色id
        //删除中间表数据
        roleMapper.delRoleMenuByRoleID(id);
        roleMapper.delRolePermissionByRoleID(id);
        roleMapper.delEmployeeRoleByRoleID(id);
        super.del(id);
    }

    @Override
    public void patchDelete(Long[] ids) {
        for (Long id:ids){
            del(id);
        }
    }

    //抽取公共方法供添加修改时调用
    private void addData(Role role){
        List<Long> menus = role.getMenus();
        if (menus.size()>0){
            roleMapper.addRoleMenu(role.getId(),menus);
        }
        List<Long> permissions = role.getPermissions();
        if (menus.size()>0){
            roleMapper.addRolePermissions(role.getId(),permissions);
        }
    }
}
